package com.klhappy.houyuan.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.klhappy.houyuan.bean.FeedBackBean;
import com.klhappy.houyuan.constant.KeyConstant;
import com.klhappy.houyuan.dialog.Photograph;
import com.klhappy.houyuan.utils.NotifyMethod;
import com.klhappy.houyuan.utils.imageselector.Bimp;
import com.klhappy.houyuan.utils.imageselector.FileUtils;
import com.klhappy.houyuan.utils.imageselector.ImageGridActivity;
import com.klhappy.houyuan.utils.imageselector.ImageItem;
import com.klhappy.houyuan.utils.imageselector.PhotoActivity;
import com.klhappy.houyuan.utils.okhttp.BaseBeanCallback;
import com.klhappy.houyuan.utils.okhttp.ImgBean;
import com.klhappy.houyuan.utils.okhttp.OkHttpUtils;
import com.klhappy.houyuan.view.AbsActivity;
import com.klhappy.houyuan.R;
import com.klhappy.houyuan.bean.BaseJsonBean;
import com.klhappy.houyuan.constant.UrlConstant;
import com.klhappy.houyuan.interfaces.BaseDealPicture;
import com.klhappy.houyuan.interfaces.CallBackInterModle;
import com.klhappy.houyuan.modle.JiaYuanModle;
import com.klhappy.houyuan.utils.PictureDeal;
import com.klhappy.houyuan.view.banner.DisplayUtil;
import com.squareup.okhttp.Request;
import com.squareup.picasso.Picasso;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2015/11/16.
 */
public class FeedBackActivity extends AbsActivity implements CallBackInterModle {
    private static final int REQUEST_CODE_TAKE_PICTURE = 12;
    public static final String AVG = "FeedBackActivity";
    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.et_idea)
    EditText et_idea;
    @InjectView(R.id.pictrue_gv)
    GridView pictrue_gv;

    @OnClick(R.id.click_ra)
    public void click_ra() {
        finish();
    }

    @OnClick(R.id.btn_submit)
    public void btn_submit() {
        String str = et_idea.getText().toString();
        if ((null == str || str.trim().length() == 0) && Bimp.selectBitmap.size() == 0) {
            Toast.makeText(this, "请先填写意见...", Toast.LENGTH_SHORT).show();
            return;
        }

        list = new ArrayList<>();
        for (int i = 0; i < Bimp.selectBitmap.size(); i++) {
            FeedBackBean backBean = new FeedBackBean();
            backBean.setFileName(getFileName(Bimp.selectBitmap.get(i).getImagePath()));
            backBean.setFile(new File(Bimp.selectBitmap.get(i).getImagePath()));
            list.add(backBean);
        }
        setIdea(str, list);
    }

    public static Bitmap bimap;
    private JiaYuanModle modle;
    private Photograph photograph;
    private GridAdapter adapter;
    private String filePath = "";
    private String fileName = "";
    private List<FeedBackBean> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.feedback);
        ButterKnife.inject(this);
        title.setText("意见反馈");

        modle = new JiaYuanModle(this);
        modle.setCallBackInterModle(this);

        Bimp.max = 0;
        Bimp.selectBitmap.clear();
        bimap = BitmapFactory.decodeResource(getResources(),
                R.drawable.icon_addpic_unfocused);

        pictrue_gv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        pictrue_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == Bimp.selectBitmap.size()) {
                    photograph = new Photograph(FeedBackActivity.this) {
                        @Override
                        public void doGoToImg() {
                            this.dimiss();
                            Intent intent = new Intent(FeedBackActivity.this, ImageGridActivity.class);
                            Bimp.max = 0;//重置为0，以便刷新
                            startActivity(intent);
                        }

                        @Override
                        public void doGoToPhone() {
                            this.dimiss();
                            photo();
                        }
                    };
                    photograph.show();
                } else {
                    Intent intent = new Intent(FeedBackActivity.this, PhotoActivity.class);
                    intent.putExtra("ID", position);
                    startActivity(intent);
                }
            }
        });
        NotifyMethod.getInstance().addObserver(AVG, new NotifyMethod.NotifyListener() {
            @Override
            public void notify(Object o) {
                showToastx((String)o);
                finish();
            }
        });
    }


    @Override
    public void CallBackFromModle(String url, BaseJsonBean o) {
        if (url.equals(UrlConstant.CONTENT_URL)) {
            if (o.getCode() == 200) {
                showToastx(o.getMsg());
                finish();
            } else {
                showToastx(o.getMsg());
            }
        }
    }

    public void photo() {
        if ("".equals(filePath)) {
            filePath = FileUtils.getImagePath(this);
        }
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath, fileName)));
        startActivityForResult(openCameraIntent, REQUEST_CODE_TAKE_PICTURE);
    }

    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;
        int creenW, creenH;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            this.creenW = dm.widthPixels;
            this.creenH = dm.heightPixels;
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }

        public int getCount() {
            if (Bimp.selectBitmap.size() == 9) {
                return 9;
            }
            return (Bimp.selectBitmap.size() + 1);
        }

        public Object getItem(int arg0) {
            return null;
        }

        public long getItemId(int arg0) {
            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                ViewGroup.LayoutParams layoutParams = holder.image.getLayoutParams();
                layoutParams.height = creenW / 5;
                layoutParams.width = creenW / 5;
                holder.image.setLayoutParams(layoutParams);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == Bimp.selectBitmap.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.drawable.icon_addpic_unfocused));
                if (position == 9) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                int size = DisplayUtil.getWindowWidth(FeedBackActivity.this) / 6;
                Picasso.with(FeedBackActivity.this)
                        .load(new File(Bimp.selectBitmap.get(position).getImagePath()))
                        .placeholder(R.drawable.default_img)
                        .error(R.drawable.default_img)
                        .centerCrop()
                        .resize(size, size)
                        .into(holder.image);
            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //图片列表显示
        adapter = new GridAdapter(this);
        adapter.update();
        pictrue_gv.setAdapter(adapter);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Bimp.selectBitmap.size() < 9 && requestCode == REQUEST_CODE_TAKE_PICTURE) {
            ImageItem takePhoto = new ImageItem();
            if (resultCode == RESULT_OK) {//拍照返回
                takePhoto.setImagePath(filePath + File.separator + fileName);
                Bimp.selectBitmap.add(takePhoto);
                fileName = "";
            } else if (null != data && null != data.getExtras() && null != data.getExtras().get("data")) {
                Bitmap bm = (Bitmap) data.getExtras().get("data");
                FileUtils.saveBitmap(bm, fileName);
                takePhoto.setBitmap(bm);
                Bimp.selectBitmap.add(takePhoto);
                fileName = "";
            }
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    adapter.notifyDataSetChanged();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void loading() {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    if (Bimp.max == Bimp.selectBitmap.size()) {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                        break;
                    } else {
                        Bimp.max += 1;
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                }
            }
        }).start();
    }

    //意见反馈
    public void setIdea(String idea, List<FeedBackBean> list) {
        File[] files = new File[list.size()];
        for (int i = 0; i < files.length; i++) {
            // 照相空指针
            files[i] = list.get(i).getFile();
        }

        PictureDeal deal = new PictureDeal(this, idea);
        deal.dealPicture(files);
    }

    public String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }
    }

}
